﻿using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using NewRetail.Application.Components.Account.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Authorization;
using Volo.Abp.Json;

namespace NewRetail.Application.Components.Account
{
    public interface IUserAccountService : IApplicationService
    {
        Task<UserModel> GetCurrentLoginUser();
    }

    public class UserAccountService : MyApplicationService, IUserAccountService
    {
        private readonly HttpClient httpClient;
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IJsonSerializer jsonSerializer;
        public UserAccountService(IHttpClientFactory httpClientFactory, IConfiguration configuration,
            IHttpContextAccessor httpContextAccessor,
            IJsonSerializer jsonSerializer)
        {
            this.httpClient = httpClientFactory.CreateClient(nameof(UserAccountService));
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
            this.httpContextAccessor.HttpContext.Should().NotBeNull();
            this.jsonSerializer = jsonSerializer;

            var address = configuration["current_api_address"];
            address.Should().NotBeNullOrEmpty();
            this.httpClient.BaseAddress = new Uri($"{address}/api/platform/");
        }

        string GetBearerTokenOrThrow()
        {
            var flag = this.httpContextAccessor.HttpContext.Request.Headers.TryGetValue(HeaderNames.Authorization, out var val);
            if (flag)
            {
                var token = ((string)val).Split(' ').Skip(1).FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(token))
                {
                    return token;
                }
            }

            throw new BusinessException();
        }

        public async Task<UserModel> GetCurrentLoginUser()
        {
            try
            {
                var token = this.GetBearerTokenOrThrow();

                using var message = new HttpRequestMessage(HttpMethod.Get, $"api/Authorize/GetUserInfo?tokenStr={token}");
                message.Content = null;
                message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

                //message.Headers.Clear();

                foreach (var h in this.httpContextAccessor.HttpContext.Request.Headers)
                {
                    //message.Headers.Add(h.Key, h.Value.ToArray());
                }

                using var response = await this.httpClient.SendAsync(message);
                response.EnsureSuccessStatusCode();

                var json = await response.Content.ReadAsStringAsync();
                var model = this.jsonSerializer.Deserialize<UserModel>(json, camelCase: false);

                if (model == null || model.UID <= 0)
                {
                    throw new BusinessException("xx");
                }

                return model;
            }
            catch (Exception e)
            {
                this.Logger.LogException(e);
                throw new AbpAuthorizationException();
            }
        }
    }
}
